package org.csu.jpetstore.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeQueryResponse;
import org.csu.jpetstore.common.CommonResponse;
import org.csu.jpetstore.entity.AlipayBean;
import org.csu.jpetstore.service.OrderService;
import org.csu.jpetstore.util.AlipayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author CSU_Luoyuhang
 */
@Controller
@RequestMapping(value = "/orders")
public class AliPayController {
    @Autowired
    AlipayUtil alipayUtil;
    @Autowired
    private OrderService orderService;

    @PostMapping(value = "/orders/alipay/{orderId}")
    @ResponseBody
    //String outTradeNo, String subject, String totalAmount, String body
    public CommonResponse<String> alipay(
            AlipayBean alipayBean,
            @PathVariable("orderId") String orderId,
            @RequestParam(name = "subject") String subject,
            @RequestParam(name = "TotalAmount") String TotalAmount) throws AlipayApiException {

        return CommonResponse.createForSuccess(alipayUtil.pay(alipayBean, orderId, subject, TotalAmount));
    }

    @GetMapping(value = "/return")
    @ResponseBody
    //String outTradeNo, String subject, String totalAmount, String body
    public String returnUrl(HttpServletRequest request) throws AlipayApiException {
        String out_trade_no = request.getParameter("out_trade_no");
        AlipayTradeQueryResponse response = alipayUtil.tradeCheck(out_trade_no);
        String trade_status = response.getTradeStatus();
        if (trade_status.equals("TRADE_SUCCESS")) {
            orderService.updateOrder(out_trade_no);
        }
        String returnUrl = "localhost:8088/view/catalog-main.html";
        //需要一个返回的网址
        return null;
    }

    @PostMapping(value = "/notify")
    @ResponseBody
    //String outTradeNo, String subject, String totalAmount, String body
    public String notifyUrl(HttpServletRequest request) throws AlipayApiException {

        return null;
    }
}
